package ddd.ajava.chapter2.question3;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import ddd.ajava.chapter2.question1.Person;
import ddd.ajava.util.StringUtil;

/**
 * @author lenovo
 * 从文本文件读入，反射赋给类实例步骤如下:
 * 1.读入文件
 * 2.分析文件
 * 3.反射赋值
 * 4.打印实例信息测试赋值情况
 */
public class SetAttrToInstance {
	private Person person=new Person();
	private Class clazz=person.getClass();
	
	public static void main(String[] args) {
		SetAttrToInstance satt=new SetAttrToInstance();
		satt.readInFile();
		System.out.println(satt.toString());
	}
	
	private void readInFile(){
		String path="src\\ddd\\ajava\\chapter2\\question2\\Person.txt";
		try {
			BufferedReader bufferReader=new BufferedReader(new InputStreamReader(new FileInputStream(path)));
			String text=bufferReader.readLine();
			while(text.length()>0){
				analyzeFile(text);
				text=bufferReader.readLine();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
//			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void analyzeFile(String text){
		String[] values=text.split("=");
		String methodName="set"+StringUtil.firstCharToUpper(values[0]);
		setAttr(methodName.trim(),values[1].trim());
	}
	
	private void setAttr(String methodName,Object value){
		try {
			Method[] method=clazz.getDeclaredMethods();
			for(Method m:method){
				if(m.getName().equals(methodName)){
					Class[] paramType=m.getParameterTypes();
					String type=paramType[0].getCanonicalName();
					m.invoke(person,Class.forName(type).getConstructor(String.class).newInstance(value));
					return;
				}
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}
	}
	
	public String toString(){
		return "idNo:"+person.getIdNo()+",name:"+person.getName()+",age:"
		+person.getAge()+",sex:"+person.getSex()+",isMerried:"
		+person.getIsMerried();
	}
}
